package com.tdam2014.grupo3.tasks;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;

import android.content.Context;
import android.os.AsyncTask;

import com.tdam2014.grupo3.R;
import com.tdam2014.grupo3.db.PeopleDatabaseHelper;
import com.tdam2014.grupo3.db.PhotoSetDatabaseHelper;
import com.tdam2014.grupo3.entities.PhotoSet;
import com.tdam2014.grupo3.flickr.Flickr;
import com.tdam2014.grupo3.flickr.FlickrException;
import com.tdam2014.grupo3.flickr.interfaces.PhotoSetInterface;
import com.tdam2014.grupo3.flickrviewer.FlickrViewer;
import com.tdam2014.grupo3.interfaces.UpdateableUI;
import com.tdam2014.grupo3.utils.NetworkUtils;

public class UpdatePhotoSetsListTask extends AsyncTask<String, Object, ArrayList<PhotoSet>> {
	
	private Context context;
	private String peopleNsid;
	private UpdateableUI updateableUI;
	private boolean isConnected;
	
	public UpdatePhotoSetsListTask(Context context, String peopleNsid) {
		super();
		this.context = context;
		this.peopleNsid = peopleNsid;
	}

	public UpdatePhotoSetsListTask(Context context, String peopleNsid,
			UpdateableUI updateableUI) {
		super();
		this.context = context;
		this.peopleNsid = peopleNsid;
		this.updateableUI = updateableUI;
	}

	@Override
	protected void onPreExecute() {
		if(updateableUI != null) updateableUI.onStartUpdate();
	}

	@Override
	protected ArrayList<PhotoSet> doInBackground(String... params) {
		isConnected = NetworkUtils.isOnline(context);
		if(!isConnected) {
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		Flickr flickr = new Flickr(FlickrViewer.API_KEY);
		PhotoSetInterface psi = flickr.getPhotoSetInterface();
		
		try {
			return psi.getList(params[0]);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FlickrException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	@Override
	protected void onPostExecute(ArrayList<PhotoSet> result) {
		if (result != null) {
			if(!result.isEmpty()) {
				PhotoSetDatabaseHelper photoSetDatabaseHelper = new PhotoSetDatabaseHelper(context);
				photoSetDatabaseHelper.savePhotoSets(result, peopleNsid);
				
				PeopleDatabaseHelper peopleDatabaseHelper = new PeopleDatabaseHelper(context);
				int countPhotoSets = peopleDatabaseHelper.getPeopleCountPhotoSets(peopleNsid);
				if(countPhotoSets != -1 && countPhotoSets != result.size()) {
					peopleDatabaseHelper.updatePeopleCountPhotoSets(peopleNsid, result.size());
				}
			}
			
			if(updateableUI != null) updateableUI.onFinishUpdate();
		}
		else if(updateableUI != null) {
			if(isConnected) updateableUI.informError(context.getResources().getString(R.string.error_getting_photosets));
			else updateableUI.informError(context.getResources().getString(R.string.not_connected));
		}
	}
}
